﻿using System;
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;

/// <summary>
/// 场景管理器
/// </summary>
public class SceneMgr : MonoBehaviour
{
    public static SceneMgr Instance;

    /// <summary>
    /// 场景
    /// </summary>
    public enum Scene
    {
        /// <summary>
        /// 启动界面
        /// </summary>
        Launch,
        /// <summary>
        /// 登录场景
        /// </summary>
        Login,
        /// <summary>
        /// 游戏场景
        /// </summary>
        Game
    }

    /// <summary>
    /// 上一个场景
    /// </summary>
    public Scene lastScene;
    /// <summary>
    /// 目标场景
    /// </summary>
    public Scene targetScene;
    /// <summary>
    /// 切换场景前
    /// </summary>
    public Action OnSceneChangeBefore;
    /// <summary>
    /// 开始切换场景
    /// </summary>
    public Action OnSceneChangeStart;
    /// <summary>
    /// 切换场景完成后
    /// </summary>
    public Action OnSceneChangeAfter;
    /// <summary>
    /// 是否在加载中
    /// </summary>
    public bool isLoading;

    SceneChangeView changeView;
    /// <summary>
    /// 初始化
    /// </summary>
    public void Init()
    {
        Instance = this;
        isLoading = false; 
    }

    public void LoadScene(Scene scene)
    {
        isLoading = true;
        changeView = UIMgr.Instance.Show<SceneChangeView>();
        StartCoroutine(LoadLevel(scene.ToString()));
    }

    public void SceneReady()
    {
        if(!isLoading)
        {
            return;
        }
        lastScene = targetScene;
        isLoading = false;
        StartCoroutine(changeView.Hide());
    }

    private IEnumerator LoadLevel(string level)
    {
        if (OnSceneChangeBefore != null)
        {
            OnSceneChangeBefore();
        }

        yield return changeView.Show();

        if (OnSceneChangeStart != null)
        {
            OnSceneChangeStart();
        }
         
        yield return null;
        Resources.UnloadUnusedAssets();
        GC.Collect();
        yield return null;

        SceneManager.LoadScene(level);

        if (OnSceneChangeAfter != null)
        {
            OnSceneChangeAfter();
        }

        SceneReady();
    }
}